package cn.haixiang.org.service.impl;

import cn.haixiang.org.domain.Department;
import cn.haixiang.org.domain.Employee;
import cn.haixiang.org.mapper.DepartmentMapper;
import cn.haixiang.org.query.DepartmentQuery;
import cn.haixiang.org.service.IDepartmentService;

import cn.haixiang.basice.util.PageList;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

@Service
@Transactional(readOnly = true,propagation = Propagation.SUPPORTS)
public class DepartmentServiceImpl implements IDepartmentService {
    @Autowired
    private DepartmentMapper mapper;

    @Override
    public List<Department> findAll() {
        return mapper.findAll();
    }

    @Override
    public Department findById(Long id) {
        return mapper.findById(id);
    }

    @Override
    public void update(Department department) {
        mapper.update(department);
    }

    @Override
    public void delete(Long id) {
        mapper.delete(id);
    }

    @Override
    public void add(Department department) {
    mapper.add(department);
    }

    @Override
    public PageList<Department> queryByPage(DepartmentQuery query) {
        // 查询 条数
        Integer totals = mapper.queryByCount(query);
        if (null == totals || 0 == totals){
            return new PageList<Department>(0,new ArrayList<>());//前端不想要null值所以要选0条
        }
        // 查询数据
        List<Department> rows = mapper.queryByPage(query);
        return new PageList<>(totals,rows);
    }

    @Override
    public void batchDelete(List<Long> ids) {
        mapper.batchDelete(ids);

    }

    //查询所有的简单玩法
    @Override
    public List<Department> tree(){
        ArrayList<Department> result = new ArrayList<>();//新建一个department的list
        //查询出所有的数据
        List<Department> allDepartments = mapper.findAll();
        //用foreach循环在内存中装数据
        for (Department dept : allDepartments) {
            if (null == dept.getParentId()){
                // 这就是一级数据
                result.add(dept);
            }else {
                // 这个是儿子 dept对象 它不是爹 那么它有几个爹
                for (Department parent : allDepartments) {
                    if (dept.getParentId().equals(parent.getId())){
                        parent.getChildren().add(dept);
                        break;
                    }
                }
            }
        }
        return result;
    }

    @Override
    public List<Employee> findEmpById(Long id) {
        return mapper.findEmpById(id);
    }


}